import { Component, Inject, OnInit } from '@angular/core';
import { ControlWidget } from '@delon/form';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-itcore-img-upload',
  template: `
    <sf-item-wrap [id]="id" [schema]="schema" [ui]="ui" [showError]="showError" [error]="error" [showTitle]="schema.title">
      <nz-upload
        class="avatar-uploader"
        [nzAction]="action"
        [nzName]="paramName"
        nzListType="picture-card"
        [nzShowUploadList]="false"
        [nzBeforeUpload]="beforeUpload"
        (nzChange)="handleChange($event)"
      >
        <ng-container *ngIf="!value">
          <i class="upload-icon" nz-icon [nzType]="loading ? 'loading' : 'plus'"></i>
          <div class="ant-upload-text">上传</div>
        </ng-container>
        <img *ngIf="value" [src]="value" style="width: 100%" />
        <div *ngIf="value" class="ant-upload-text" (click)="handlePreview($event); $event.stopPropagation()">预览</div>
      </nz-upload>
      <nz-modal [nzVisible]="previewVisible" [nzContent]="modalContent" [nzFooter]="null" (nzOnCancel)="previewVisible = false">
        <ng-template #modalContent>
          <img [src]="previewImage" [ngStyle]="{ width: '100%' }" />
        </ng-template>
      </nz-modal>
    </sf-item-wrap>
  `,
  styles: [
    `
      :host ::ng-deep .avatar-uploader > .ant-upload {
        width: 128px;
        height: 128px;
      }
    `,
  ],
})
// 头像小部件，单张图片上传
export class ImgUploadWidgetComponent extends ControlWidget implements OnInit {
  static readonly KEY = 'itcore-img-upload';
  // 加载
  loading = false;
  // 图片格式限制  ex:（image/jpeg,image/png） 多个按照逗号分隔
  imageType: string;
  // 上传地址
  action: string;
  // 文件上传参数
  paramName: string;
  // 图片
  imageSize: number;
  // 失败回调，返回错误信息
  errorMsgCallback: any;
  // 返回 后台返回的value 地址所带的
  imageBaseUrl: string;
  // 预览
  previewImage: string | undefined = 'api/Common/UploadImage';
  // 预览图片是否显示
  previewVisible = false;

  ngOnInit(): void {
    this.imageType = this.ui.imageType || 'image/jpeg,image/png';
    this.imageSize = this.ui.imageSize || 2;
    this.action = this.ui.action || 'api/Common/UploadImage';
    this.paramName = this.ui.paramName || 'file';
    this.imageBaseUrl = this.ui.imageBaseUrl || '';
    this.errorMsgCallback = this.ui.errorMsgCallback || this.errorMsg;
    this.handlePreview = this.ui.handlePreview || this.handlePreview;
  }
  errorMsg(msg: string) {
    return msg;
  }
  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = this.imageType.split(',').indexOf(file.type) > -1;
      if (!isJpgOrPng) {
        this.errorMsgCallback(`只能上传【${this.imageType}】类型的图片`);
        observer.complete();
        return;
      }
      const isLimitSize = file.size / 1024 / 1024 < this.imageSize;
      if (!isLimitSize) {
        this.errorMsgCallback(`图片大小不能超过【${this.imageSize}】MB`);
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLimitSize);
      observer.complete();
    });
  }

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        if (info.file.response && info.file.response.Type === 200) {
          this.change(this.imageBaseUrl + info.file.response.Data);
        } else {
          this.errorMsgCallback(info.file.response ? info.file.response.Message : '服务器异常！');
        }
        this.loading = false;
        break;
      case 'error':
        this.errorMsgCallback(`Network error`);
        this.loading = false;
        break;
    }
  }
  handlePreview = async (e) => {
    this.previewImage = this.value;
    this.previewVisible = true;
  }
  change(value: string) {
    if (this.ui.change) {
      this.ui.change(value);
    }
    this.setValue(value);
  }
}
